<template>
  <div class="fx-collapse">
    <slot></slot>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onBeforeMount, onBeforeUnmount, PropType, provide, ref } from 'vue'
import mitt, { Emitter } from 'mitt'
import { useModelWatch } from '@/base/hooks'

export type CollapseSelected = string | number | Array<string | number>

interface CollapseProps {
  modelValue: CollapseSelected;
  hideArrow: boolean;
}

export default defineComponent({
  name: 'fxCollapse',
  props: {
    modelValue: {
      type: [String, Number, Array] as PropType<CollapseSelected>,
      default: ''
    },
    // 隐藏箭头
    hideArrow: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  setup (props: CollapseProps) {
    // collapse mitt
    const collapseMitt: Emitter = mitt()
    // 当前选中
    const currentSelect = ref(props.modelValue)
    useModelWatch(() => props.modelValue, currentSelect)
    // mitt
    provide('collapseMittEmit', collapseMitt.emit)
    // 当前选中
    provide('collapseSelected', computed(() => currentSelect.value))
    // 隐藏箭头
    provide('collapseHideArrow', computed(() => props.hideArrow))
    // 点击开启/关闭事件
    const handleCollapseItemChange = (name: string | number | undefined): void => {
      if (name === undefined) return
      if (currentSelect.value instanceof Array) {
        const index = currentSelect.value.findIndex((item: string | number) => item === name)
        if (index >= 0) {
          currentSelect.value.splice(index, 1)
        } else {
          currentSelect.value.push(name)
        }
      } else {
        currentSelect.value = currentSelect.value === name ? '' : name
      }
    }

    onBeforeMount(() => {
      collapseMitt.on<string | number | undefined>('collapseItemChange', handleCollapseItemChange)
    })

    onBeforeUnmount(() => {
      collapseMitt.off('collapseItemChange', handleCollapseItemChange)
    })

    return {}
  }
})
</script>
